package com.oscar.ehome.view.setview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.fragment.BaseFragment;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.setbean.SetMessageBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.progressview.ObservableScrollView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.AddMemberActivity;
import com.oscar.ehome.view.pageview.BannerWebActivity;
import com.oscar.ehome.view.pageview.SigninTwoActivity;
import com.oscar.ehome.view.setview.view.SetingView;
import com.oscar.ehome.view.teamview.TeamDetailActivity;
import com.umeng.analytics.MobclickAgent;

import org.apache.commons.collections.MapUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by on 2017/5/19 16:11.
 * 我的页面
 *
 * @author mengwanhe
 */

public class SetFragment extends BaseFragment<SetingView, SetPresenter> implements SetingView, ObservableScrollView.ScrollViewListener {

    /**
     * 增员
     */
    @BindView(R.id.liear_addpeople)
    LinearLayout liearAddpeople;
    /**
     * 支付
     */
    @BindView(R.id.liear_pay)
    LinearLayout liearPay;
    /**
     * 我的下载
     */
    @BindView(R.id.liear_mydownload)
    LinearLayout liearMydownload;
    /**
     * 学习历史记录
     */
    @BindView(R.id.liear_history)
    LinearLayout liearHistory;
    /**
     * 我的发布
     */
    @BindView(R.id.liear_issue)
    LinearLayout liearIssue;
    /**
     * 我的二维码
     */
    @BindView(R.id.liear_twocode)
    LinearLayout liearTwocode;
    /**
     * 意见反馈
     */
    @BindView(R.id.liear_advise)
    LinearLayout liearAdvise;
    /**
     * 设置
     */
    @BindView(R.id.liear_setting)
    LinearLayout liearSetting;
    /**
     * 头像
     */
    @BindView(R.id.mine_head)
    ImageView mineHead;
    /**
     * 姓名
     */
    @BindView(R.id.mine_name)
    TextView mineName;
    /**
     * 职级
     */
    @BindView(R.id.mine_leve)
    TextView mineLeve;
    /**
     * 性别
     */
    @BindView(R.id.sex_img)
    ImageView sexImg;
    /**
     * 签到
     */
    @BindView(R.id.qiandao)
    ImageView qiandao;
    /**
     * 说明文档
     */
    @BindView(R.id.liear_show)
    LinearLayout liearShow;
    /**
     * 我的
     */
    @BindView(R.id.myset_layout)
    RelativeLayout mysetLayout;
    /**
     * 评级
     */
    @BindView(R.id.liear_pingji)
    LinearLayout liear_pingji;
    /**
     * 工号
     */
    @BindView(R.id.gonghao)
    TextView gonghao;
    /**
     * 支付状态
     */
    @BindView(R.id.set_pay_text)
    TextView setPayText;
    /**
     * 折扣
     */
    @BindView(R.id.discount_text)
    TextView discount_text;
    /**
     * 评级Imageview
     */
    @BindView(R.id.pingji_img)
    ImageView pingji_img;
    /**
     * 增员Imageview
     */
    @BindView(R.id.zengyuan_img)
    ImageView zengyuan_img;
    /**
     * 银行卡Imageview
     */
    @BindView(R.id.idcard_img)
    ImageView idcard_img;
    /**
     * 中间行设置
     */
    @BindView(R.id.setmessage_layout)
    LinearLayout setmessageLayout;

    /**
     * 我的下载图标
     */
    @BindView(R.id.mydownload_img)
    ImageView mydownload_img;
    /**
     * 学习历史图标
     */
    @BindView(R.id.history_img)
    ImageView history_img;
    /**
     * 我的发布图标
     */
    @BindView(R.id.issue_img)
    ImageView issue_img;
    /**
     * 我的二维码图标
     */
    @BindView(R.id.twocode_img)
    ImageView twocode_img;
    /**
     * 说明文档图标
     */
    @BindView(R.id.shuoming_img)
    ImageView shuoming_img;
    /**
     * 设置图标
     */
    @BindView(R.id.shehzhi_img)
    ImageView shehzhi_img;
    /**
     * 意见图标
     */
    @BindView(R.id.yijian_img)
    ImageView yijian_img;
    /***
     * 工号布局
     */
    @BindView(R.id.gonghao_relout)
    RelativeLayout gonghaoRelout;
    /**
     * 滑动的
     */
    @BindView(R.id.soll_img)
    ImageView sollImg;
    /**
     * 滑动效果
     */
    @BindView(R.id.drozoomscoll)
    ObservableScrollView drozoomscoll;
    /**
     * 标题
     */
    @BindView(R.id.tv_titlebor)
    TextView tvTitlebor;
    /**
     *
     */
    @BindView(R.id.toolbar)
    RelativeLayout toolbar;
    /**
     *
     */
    @BindView(R.id.spite_line)
    View spiteLine;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.zhifuhouyincang)
    View view3;
    @BindView(R.id.liear_myquestion)
    LinearLayout liearMyquestion;

    Unbinder unbinder;
    private View view;

    SetPresenter setPresenter;
    String token = "";
    SetMessageBean setMessageBean;
    UserBean userBean;
    int discount = 0;//是否有折扣
    private int height;
    String leve = "";//职级


    private Bitmap head;// 头像Bitmap
    private static String path = "/sdcard/myHead/";// sd路径

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_set, null);
        unbinder = ButterKnife.bind(this, view);
        setColor();
        init();
        initData();
        initListeners();
        return view;
    }

    @Override
    protected SetPresenter createPresenter() {
        setPresenter = new SetPresenter(this);
        return setPresenter;
    }

    /**
     * 改变颜色
     */
    public void setColor() {
        TintManager.setTint(pingji_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(qiandao, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(zengyuan_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(idcard_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(mydownload_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(history_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(issue_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(twocode_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(shuoming_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(shehzhi_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        TintManager.setTint(yijian_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        mysetLayout.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
    }

    /**
     * 初始化view
     */
    private void init() {
        token = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken();

        String user = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUserBean();
        userBean = new Gson().fromJson(user, UserBean.class);
        if (userBean != null) {

            if ("2".equals(userBean.getIsManager())) {// 其他人员
                setmessageLayout.setVisibility(View.GONE);
                liearIssue.setVisibility(View.GONE);
                //  liearMydownload.setVisibility(View.GONE);
                liearHistory.setVisibility(View.GONE);
                liearIssue.setVisibility(View.GONE);
                liearTwocode.setVisibility(View.GONE);
                view1.setVisibility(View.GONE);
                view2.setVisibility(View.GONE);
                mysetLayout.setEnabled(false);
            } else {//内勤人员
                setmessageLayout.setVisibility(View.VISIBLE);
                liearIssue.setVisibility(View.VISIBLE);
                // liearMydownload.setVisibility(View.VISIBLE);
                liearHistory.setVisibility(View.VISIBLE);
                liearIssue.setVisibility(View.VISIBLE);
                liearTwocode.setVisibility(View.VISIBLE);
                view1.setVisibility(View.VISIBLE);
                view2.setVisibility(View.VISIBLE);
                mysetLayout.setEnabled(true);
            }
            if ("1".equals(userBean.getIsReleaseOaNotify())) {//显示发布消息
                liearIssue.setVisibility(View.VISIBLE);
            } else {
                liearIssue.setVisibility(View.GONE);
            }
        }
    }


    /**
     * 请求数据
     */
    public void initData() {
        setPresenter.getMessages(token);
        showLoading();
    }


    @OnClick({R.id.liear_addpeople, R.id.liear_pay, R.id.liear_mydownload, R.id.liear_history, R.id.liear_issue, R.id.liear_show,
            R.id.liear_twocode, R.id.liear_advise, R.id.liear_setting, R.id.myset_layout, R.id.liear_qiandao, R.id.liear_pingji, R.id.liear_myquestion})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.myset_layout://进入详情页
                if (setMessageBean != null) {
                    Intent intent_my = new Intent(getActivity(), TeamDetailActivity.class);
                    intent_my.putExtra("set", 1);
                    intent_my.putExtra("id", setMessageBean.getId());
                    startActivity(intent_my);
                }
                break;
            case R.id.liear_pingji://评级
                Intent intentpingji = new Intent(getActivity(), RateListActivity.class);
                String addapp = new Gson().toJson(setMessageBean);
                intentpingji.putExtra("message", addapp);
                startActivity(intentpingji);
                break;
            case R.id.liear_qiandao://签到
                if (setMessageBean != null) {
//                    String number = setMessageBean.getNo();
//                    if (number != null && !number.equals("")) {
                    if (setMessageBean.getIsPay() != null && "1".equals(setMessageBean.getIsPay())) {
                        startActivity(new Intent(getActivity(), SigninTwoActivity.class));
                    } else {
                        Toast.makeText(getActivity(), "请支付后进入", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getActivity(), "请支付后进入", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.liear_addpeople://增员
                if (setMessageBean != null) {
//                    String number = setMessageBean.getNo();
//                    if (number != null && !number.equals("")) {
                    if (setMessageBean.getIsPay() != null && "1".equals(setMessageBean.getIsPay())) {
                        MobclickAgent.onEvent(getActivity(), "zengyuan2");
                        Intent intent = new Intent(getActivity(), AddMemberActivity.class);
                        intent.putExtra("twocode", "page");
                        startActivity(intent);
                    } else {
                        Toast.makeText(getActivity(), "请支付后进入", Toast.LENGTH_SHORT).show();
                    }
//                    } else {
//                        Toast.makeText(getContext(), "您暂时还没有工号，请联系管理员", Toast.LENGTH_SHORT).show();
//                    }
                } else {
                    Toast.makeText(getActivity(), "您暂时还没有工号，请联系管理员", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.liear_pay://支付
                if (setMessageBean != null) {
                    if (setMessageBean.getIsPay() != null) {
                        if ("0".equals(setMessageBean.getIsPay())) {
                            String price = "";
                            if (setMessageBean.getPrice() != null) {
                                price = setMessageBean.getPrice();
                            }
                            Intent inpay = new Intent(getActivity(), PayActivity.class);
                            inpay.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            Bundle bundle = new Bundle();
                            bundle.putString("price", String.valueOf(price));
                            bundle.putString("payDesc", setMessageBean.getPayDesc());
                            if (discount != 0) {
                                bundle.putString("discount", String.valueOf(discount));
                            } else {
                                bundle.putString("discount", String.valueOf(0));
                            }
                            inpay.putExtras(bundle);
                            startActivity(inpay);
                        } else {
                            Intent inpay = new Intent(getActivity(), PaysuccesActivity.class);
                            inpay.putExtra("Payname", setMessageBean.getName());
                            inpay.putExtra("Payphone", userBean.getPhone());
                            startActivity(inpay);
                        }
                    }
                }
                break;
            case R.id.liear_mydownload://我的下载
                Intent intentdown = new Intent(getActivity(), MyDownloadActivity.class);
                startActivity(intentdown);
                break;
            case R.id.liear_history://学习历史记录
                Intent intentlean = new Intent(getActivity(), LearnHistoryActivity.class);
                startActivity(intentlean);
                break;
            case R.id.liear_issue://我的发布
                Intent intentfabu = new Intent(getActivity(), MyfabuActivity.class);
                startActivity(intentfabu);
                break;
            case R.id.liear_twocode://我的二维码
                Intent intent = new Intent(getActivity(), AddMemberActivity.class);
                intent.putExtra("twocode", "twocode");
                startActivity(intent);
                break;
            case R.id.liear_advise://意见反馈
                startActivity(new Intent(getActivity(), FeedBackActivity.class));
                break;
            case R.id.liear_show://说明文档
                Intent intent_about = new Intent(getActivity(), BannerWebActivity.class);
                intent_about.putExtra("contentsrc", C.shuoming_url);
                intent_about.putExtra("type", "shuoming");
                intent_about.putExtra("name", "");
                intent_about.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent_about);
                break;
            case R.id.liear_setting://设置
                Intent intentset = new Intent(getActivity(), SettingActivity.class);
                startActivity(intentset);
                break;
            case R.id.liear_myquestion:// 我的问题

                Intent intent_question = new Intent(getActivity(), MyQuestionActivity.class);
                startActivity(intent_question);

                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void getMessage(SetMessageBean rateListBean) {
        dismissLoading();
        if (getActivity() != null) {
            if (MapUtils.getString(CommonUtils.dakaMap, "s") != null && !"".equals(MapUtils.getString(CommonUtils.dakaMap, "s"))) {
                SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setUserMessage(MapUtils.getString(CommonUtils.dakaMap, "s"));
            }
        }
        Log.e("xingbiesss", "init: " + rateListBean.getSex());
        if (rateListBean.getSex() != null) {
            if ("女".equals(rateListBean.getSex())) {
                sexImg.setImageResource(R.mipmap.nv);
            } else if ("男".equals(rateListBean.getSex())) {
                sexImg.setImageResource(R.mipmap.por_label_sex);
            }
        }
        if (rateListBean.getIsNeedPay().getIsNeedPay() != null && rateListBean.getIsNeedPay().getIsNeedPay().equals("0")) {
            view3.setVisibility(View.GONE);
            liearPay.setVisibility(View.GONE);
            rateListBean.setIsPay("1");
        } else {
            view3.setVisibility(View.VISIBLE);
            liearPay.setVisibility(View.VISIBLE);
        }
        if (rateListBean != null) {
            setMessageBean = rateListBean;
            mineName.setText(rateListBean.getName());

            if (setMessageBean.getRoleMobile() != null) {
                if (setMessageBean.getRoleMobile().getRoleName() != null) {
                    mineLeve.setText(setMessageBean.getRoleMobile().getRoleName());
                    leve = setMessageBean.getRoleMobile().getRoleName();
                } else {

                    mineLeve.setText("暂无");
                }
            } else {

                mineLeve.setText("暂无");
            }
            if (rateListBean.getNo() != null && !"".equals(rateListBean.getNo())) {//工号
                if ("准会员".equals(leve)) {
                    DisplayMetrics dm = getResources().getDisplayMetrics();
                    RelativeLayout.LayoutParams linearParams =  (RelativeLayout.LayoutParams)gonghaoRelout.getLayoutParams();
                    linearParams.width = dm.widthPixels/3;
                    gonghaoRelout.setLayoutParams(linearParams);
//                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) gonghaoRelout.getLayoutParams();
//                    params.width = R.dimen.pad_height_100;//设置当前控件布局的高度
//                    gonghaoRelout.setLayoutParams(params);//将设置好的布局参数应用到控件中
                    gonghao.setText("工号：暂无");
                } else {
                    gonghao.setText("工号：" + rateListBean.getNo());
                }
            } else {
                DisplayMetrics dm = getResources().getDisplayMetrics();
                RelativeLayout.LayoutParams linearParams =  (RelativeLayout.LayoutParams)gonghaoRelout.getLayoutParams();
                linearParams.width = dm.widthPixels/3;
                gonghaoRelout.setLayoutParams(linearParams);
                gonghao.setText("工号：暂无");
            }

            String img_path = rateListBean.getPhoto();
            Log.e("youxiang", "getMessage: " + C.qiniu_ip + img_path + "    " + img_path);
//            GildeUtils.imgLoadPic(getActivity(), C.qiniu_ip + img_path, mineHead, "net-p");
            GildeUtils.loadUrlImage4(C.qiniu_ip + img_path, mineHead, getActivity());
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setUserimg(img_path);

            if ("1".equals(rateListBean.getIsPay())) {
                discount = 0;
                discount_text.setVisibility(View.INVISIBLE);
                setPayText.setText("已支付");
            } else {
                setPayText.setText("支付");
                if (rateListBean.getDiscount() != null)
                    if (rateListBean.getDiscount().equals("1") || rateListBean.getDiscount().equals("0")) {
                        discount = 0;
                        discount_text.setVisibility(View.INVISIBLE);
                    } else {
                        discount_text.setVisibility(View.VISIBLE);
                        double count = Double.parseDouble(rateListBean.getDiscount()) * 10;
                        if (count < 1 && count > 0) {
                            discount = (int) count;
                            discount_text.setText("- 限时" + String.valueOf(count) + "折 -");
                        } else {
                            discount_text.setVisibility(View.INVISIBLE);
                            discount = 0;
                        }
                    }
            }

            if (rateListBean.getStarLevel() != null) {
                switch (rateListBean.getStarLevel()) {
                    case "0":
                        pingji_img.setImageResource(R.mipmap.xing0);
                        break;
                    case "1":
                        pingji_img.setImageResource(R.mipmap.xing1);
                        break;
                    case "2":
                        pingji_img.setImageResource(R.mipmap.xing2);
                        break;
                    case "3":
                        pingji_img.setImageResource(R.mipmap.xing3);
                        break;
                }
                TintManager.setTint(pingji_img, Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
//        String filepaths = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUserimg();
//        if (filepaths != null && !"".equals(filepaths)) {
//            Bitmap bit = BitmapFactory.decodeFile(filepaths);
//            mineHead.setImageBitmap(bit);// 用ImageView显示出来
//        }
        if (CommonUtils.pay == 2) {
            CommonUtils.pay = 1;
            setPresenter.getMessages(token);
        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        if (getActivity() != null)
            ToastUtil.show(getActivity(), "请求失败，请重试！");
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        ToastUtil.show(getActivity(), result);
        if (result.contains("过期")) {
            getActivity().getSharedPreferences("appbase", getActivity().MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        }
    }

    /**
     * 获取顶部图片高度后，设置滚动监听
     */
    private void initListeners() {
        tvTitlebor.setText(getString(R.string.ehome_set));
        tvTitlebor.setTextColor(getResources().getColor(R.color.transparent));
        ViewTreeObserver vto = mysetLayout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tvTitlebor.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                height = mysetLayout.getHeight();
                drozoomscoll.setScrollViewListener(SetFragment.this);
            }
        });
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {   //设置标题的背景颜色
            toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
            tvTitlebor.setTextColor(getResources().getColor(R.color.transparent));
        } else if (y > 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
//            tvTitlebor.setTextColor(getResources().getColor(R.color.white));
//            toolbar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        } else {    //滑动到banner下面设置普通颜色
            tvTitlebor.setTextColor(getResources().getColor(R.color.transparent));
            toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
    }

}
